#include "DatabaseManager.h"
#include <iostream>
#include <sqlite3.h>
using namespace std;

// 用户登录
int DatabaseManager::getUser(UserManager *userTarget, UserManager *userSrc)
{
    sqlite3 *db;
    int rc = sqlite3_open(SHMS_DB_PATH, &db);
    if (rc != SQLITE_OK)
    {
        fprintf(stderr, "打开数据库失败: %s\n", sqlite3_errmsg(db));
        return -1;
    }

    const char *sql = "select * from user where username = ? and role = ? and is_active= 1 and is_deleted = 0;";
    sqlite3_stmt *stmt;

    rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
    if (rc != SQLITE_OK)
    {
        fprintf(stderr, "准备参数失败: %s\n", sqlite3_errmsg(db));
        sqlite3_close(db);
        return -1;
    }

    // 绑定参数: 用户名
    rc = sqlite3_bind_text(stmt, 1, userSrc->getUsername().c_str(), -1, SQLITE_STATIC);
    if (rc != SQLITE_OK)
    {
        fprintf(stderr, "绑定用户名参数失败: %s\n", sqlite3_errmsg(db));
        sqlite3_finalize(stmt);
        sqlite3_close(db);
        return -1;
    }

    // 绑定参数: 角色
    rc = sqlite3_bind_text(stmt, 2, userSrc->getRole().c_str(), -1, SQLITE_STATIC);
    if (rc != SQLITE_OK)
    {
        fprintf(stderr, "绑定角色参数失败: %s\n", sqlite3_errmsg(db));
        sqlite3_finalize(stmt);
        sqlite3_close(db);
        return -1;
    }

    // 执行查询
    if (sqlite3_step(stmt) == SQLITE_ROW)
    {
        // 获取查询结果并赋值
        userTarget->setId(sqlite3_column_int(stmt, 0));
        userTarget->setUsername(reinterpret_cast<const char *>(sqlite3_column_text(stmt, 1)));
        userTarget->setPassword(reinterpret_cast<const char *>(sqlite3_column_text(stmt, 2)));
        userTarget->setRole(reinterpret_cast<const char *>(sqlite3_column_text(stmt, 3)));
        userTarget->setIsActive(sqlite3_column_int(stmt, 4));
        userTarget->setIsDeleted(sqlite3_column_int(stmt, 5));
        userTarget->setCreatedOn(reinterpret_cast<const char *>(sqlite3_column_text(stmt, 6)));
        userTarget->setUpdatedOn(reinterpret_cast<const char *>(sqlite3_column_text(stmt, 7)));
    }
    else
    {
        printf("没有找到该用户\n");
        sqlite3_finalize(stmt);
        sqlite3_close(db);
        return -1; // 没有找到用户
    }

    sqlite3_finalize(stmt);
    sqlite3_close(db);
    return 0;
}